<?php

namespace App\Http\Middleware;

use App\Traits\RespTrait;
use Closure;
use App\Common\Services\UserTokenService;
use Ramsey\Uuid\Uuid;

class HisAuthMiddleware
{
    use RespTrait;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            // 获取头部TOKEN
            $token = $request->header("TOKEN");
            if (empty($token)) {
                throw new \Exception('异常请求');
            }
            // 校验TOKEN
            $userTokenService = new UserTokenService();
            $payload = $userTokenService->verifyToken($token);

            // 将用户参数传值到控制器
            if ($payload['source'] == 'user') {
                // 用户ID
                $request->merge(['user_id'=> $payload['id'], 'jti' => $payload['jti']]);
            } else {
                // 医生ID
                $request->merge(['doctor_id'=> $payload['id'], 'jti' => $payload['jti']]);
            }
            return $next($request);
        } catch (\Exception $exception) {
            return $this->json($exception->getMessage(), [], 202);
        }
    }
}
